# -*- coding:utf-8 -*-
# @Time : 21-7-22 下午4:41 
# @Author : zdy
# @File : UIFilter.py
# desc:

import datetime
import shelve
from Class.VoltSignal import dataBase
from Class.StandardMode import ResultMode
from Class.Format import *
from Class.Devices import *
from importQT import *

class UIFilter(QtWidgets.QDialog, Ui_Filter):
    def __init__(self):
        super(UIFilter, self).__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.WindowCloseButtonHint)
        self.setFixedSize(self.width(), self.height())
        self.applyResource()
        self.setWindowTitle("查询")
        # self.rdbtnTime.setChecked(Qt.Checked)
        self.btnFilter.clicked.connect(self.btnFilter_clicked)
        self.btnOpen.clicked.connect(self.btnOpen_clicked)
        self.btnSelectAll.clicked.connect(self.btnSelectAll_clicked)

        self.modelSelect = QItemSelectionModel()
        self.modelSelectStandard = ResultMode()
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.dateTimeStart.setDateTime(datetime.datetime.now())
        self.dateTimeEnd.setDateTime(datetime.datetime.now())
        self.model = ResultMode()
        self.spinBoxDay.valueChanged.connect(self.valueChanged)
        self.spinBoxMonth.valueChanged.connect(self.valueChanged)
        self.dateTimeStart.dateTimeChanged.connect(self.valueChanged)

    def applyResource(self):
        self.setWindowIcon(getIcon())

    def btnFilter_clicked(self):
        start = None
        end = None
        name = ""
        if self.rdbtnTime.isChecked():
            try:
                start = convertPyDate(self.dateTimeStart.dateTime())  # 将QDateTime转为python类型的datetime,查询语句不接受QDateTime
                end = convertPyDate(self.dateTimeEnd.dateTime())
            except:
                QMessageBox.information(self, "提示", "时间异常")
                return
        elif self.rdbtnMonth.isChecked():
            month = int(self.spinBoxMonth.text())
            start = datetime.datetime.now() - datetime.timedelta(days=month * 30)
            end = datetime.datetime.now()
        elif self.rdbtnDay.isChecked():
            day = int(self.spinBoxDay.text())
            start = datetime.datetime.now() - datetime.timedelta(days=day)
            end = datetime.datetime.now()
        self.model.removeRows(0, self.model.rowCount())
        if self.chkName.isChecked():
            name = self.txtName.text()
        else:
            if start is None and end is None:
                QMessageBox.information(self,'提示','请设置查询条件')
                return
        results = dataBase.selectResults(start, end, name)

        if results != None:
            # inPutPath = os.path.dirname(os.path.abspath(sys.argv[0]))  # 程序运行的绝对路径
            # filepath = os.path.join(inPutPath, "data.db")
            # filepath1 = os.path.join(inPutPath,"cs", "result.dat")
            # filepath2 = os.path.join(inPutPath, "cs", "filter.dat")
            # filters = []
            # with shelve.open(filepath1, flag='c', protocol=None, writeback=False) as s:
            #     for index, r in enumerate(results):
            #         s[r.SampleId.strftime("%Y-%m-%d %H:%M:%S")] = {"DBResult": r}
            #         filters.append(r.SampleId.strftime("%Y-%m-%d %H:%M:%S"))
            # with shelve.open(filepath2, flag='c', protocol=None, writeback=False) as f:
            #     f["filter"] = filters
            device.addResults(self.model, results)
            setupTable(self.tableView, self.model, device.getresultcolHidden())

    def btnOpen_clicked(self):
        self.modelSelect = self.tableView.selectionModel()
        if self.modelSelect != None and self.modelSelect.hasSelection():
            self.accept()  # 返回值为1，或者时self.done(*)这里可以设置返回值
            self.close()
        else:
            QMessageBox.information(self, '提示', '请选择数据', QMessageBox.Ok)

    def btnSelectAll_clicked(self):
        self.tableView.selectAll()


    def valueChanged(self):
        if self.sender() == self.spinBoxDay:
            self.rdbtnDay.setChecked(True)
        elif self.sender() == self.spinBoxMonth:
            self.rdbtnMonth.setChecked(True)
        elif self.sender() == self.dateTimeStart or self.sender() == self.dateTimeEnd:
            self.rdbtnTime.setChecked(True)


import sys

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    if dataBase.initDB():
        w = UIFilter()
        w.exec()
        # modelResult = w.model
        # app.exec()
        dataBase.closeDB()
    sys.exit(0)
